<!-- CompanySidebarMenu.vue -->
<template>
  <div>
    <!-- 子菜单 -->
    <el-submenu
      v-for="route in filteredSubmenuRoutes"
      :key="getFullPath(route)"
      :index="getFullPath(route)"
    >
      <template #title>
        <i :class="route.meta?.icon || 'el-icon-s-custom'"></i>
        <span>{{ route.meta?.title }}</span>
      </template>
      <company-sidebar-menu
        v-if="route.children && route.children.length > 0"
        :routes="route.children"
        :is-hidden="isHidden"
        :parent-path="getFullPath(route)"
      />
    </el-submenu>

    <!-- 菜单项 -->
    <el-menu-item
      v-for="route in filteredMenuItemRoutes"
      :key="getFullPath(route)"
      :index="getFullPath(route)"
    >
      <template #title>
        <i :class="route.meta?.icon || 'el-icon-document'"></i>
        <span>{{ route.meta?.title }}</span>
      </template>
    </el-menu-item>
  </div>
</template>

<script>
export default {
  name: "CompanySidebarMenu",
  props: {
    routes: {
      type: Array,
      default: () => [],
    },
    isHidden: {
      type: Function,
      default: (route) => route.meta?.hidden || false,
    },
    parentPath: {
      type: String,
      default: "",
    },
  },
  computed: {
    userType() {
      return this.$store.state.recruiter.userInfo?.type || "";
    },
    filteredSubmenuRoutes() {
      return this.routes.filter(
        (route) =>
          !this.isHidden(route) &&
          route.children?.length > 0 &&
          this.hasPermission(route)
      );
    },
    filteredMenuItemRoutes() {
      return this.routes.filter(
        (route) =>
          !this.isHidden(route) &&
          (!route.children || route.children.length === 0) &&
          this.hasPermission(route)
      );
    },
  },
  methods: {
    getFullPath(route) {
      // 处理根路径
      if (route.path === "") return this.parentPath;

      // 处理带参数的路径（如:id）
      if (route.path.startsWith(":")) {
        return this.parentPath
          ? `${this.parentPath}/${route.path}`
          : route.path;
      }

      // 处理普通路径：规范化子路径并拼接父路径
      const normalizedPath = route.path.startsWith("/")
        ? route.path.slice(1) // 移除开头的斜杠
        : route.path;

      // 拼接并规范化路径（移除多余斜杠）
      return `${this.parentPath}/${normalizedPath}`.replace(/\/+/g, "/");
    },
    hasPermission(route) {
      const require = route.meta?.require || [];
      return require.length === 0 || require.includes(this.userType);
    },
  },
};
</script>